package cn.elves.model.draw.service.algorithm;

import cn.elves.model.strategy.entity.po.StrategyDetail;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class BaseDrawAlgorithm extends DrawInstanceHolder implements DrawAlgorithm {


    protected Map<Long, String[]> rateTupleMap = new ConcurrentHashMap<>();


    @Override
    public void prepare(Long strategyId, Integer strategyMode, Integer scale, List<StrategyDetail> awardRateList) {
        if (isInit(strategyId)) {
            return;
        }
        initRate(strategyId, scale, awardRateList);
    }

    protected synchronized void initRate(Long strategyId, Integer scale, List<StrategyDetail> awardRateList) {
        if (isInit(strategyId)) {
            return;
        }

        rateTupleMap.put(strategyId, makeAwardRateArr(scale, awardRateList));
    }

    protected String[] makeAwardRateArr(Integer scale, List<StrategyDetail> awardRateList) {
        return awardRateList.stream().flatMap(item -> {
            int i = item.getAwardRate().multiply(new BigDecimal(scale)).intValue();
            List<String> awardList = new ArrayList<>();
            for (int j = 0; j < i; j++) {
                awardList.add(item.getAwardId());
            }
            return awardList.stream();
        }).toArray(size -> new String[scale]);

    }

    @Override
    public boolean isInit(Long strategyId) {
        return rateTupleMap.containsKey(strategyId);
    }

    @Override
    public abstract String randomDraw(Long strategyId, List<String> excludeAwardIds);
}
